package com.creator.pangu.core.security.handler;

import com.alibaba.fastjson.JSON;
import com.creator.pangu.common.utils.R;
import com.creator.pangu.core.security.util.JWTUtil;
import com.creator.pangu.core.security.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登出成功处理类
 * 删除缓存用户信息等
 */
@Slf4j
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Resource
    private JWTUtil jwtUtil;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        log.info("into LogoutSuccessHandlerImpl method ....");

        // 获取登出用户账号
        String username = jwtUtil.getUserNameByToken(jwtUtil.getTokenByRequest(request));

        // 删除缓存中用户信息
        redisUtil.deleteObject(username);

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String jsonString = JSON.toJSONString(R.success());

        out.write(jsonString);
        out.flush();
        out.close();

    }
}
